<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简单聊天室</title>
</head>
<body>
<input type="text" id="message" placeholder="输入消息">
<button onclick="sendSingleMessage()">单条发送</button>
<button onclick="sendGroupMessage()">分组发送</button>
<button onclick="sendBroadcastMessage()">广播</button>
<button onclick="joinGroup()">加入分组</button>
<div id="chat-box"></div>

<script>
    const socket = new WebSocket('ws://127.0.0.1:2346');

    socket.onopen = function() {
        console.log('连接成功');
    };

    socket.onmessage = function(event) {
        const chatBox = document.getElementById('chat-box');
        const message = document.createElement('p');
        message.textContent = event.data;
        chatBox.appendChild(message);
    };

    socket.onclose = function() {
        console.log('连接已关闭');
    };

    function sendSingleMessage() {
        const messageInput = document.getElementById('message');
        const message = messageInput.value;
        const targetId = prompt('请输入目标用户 ID');
        if (message && targetId) {
            const data = {
                type: 'single',
                targetId: targetId,
                message: message
            };
            socket.send(JSON.stringify(data));
            messageInput.value = '';
        }
    }

    function sendGroupMessage() {
        const messageInput = document.getElementById('message');
        const message = messageInput.value;
        const groupName = prompt('请输入分组名');
        if (message && groupName) {
            const data = {
                type: 'group',
                groupName: groupName,
                message: message
            };
            socket.send(JSON.stringify(data));
            messageInput.value = '';
        }
    }

    function sendBroadcastMessage() {
        const messageInput = document.getElementById('message');
        const message = messageInput.value;
        if (message) {
            const data = {
                type: 'broadcast',
                message: message
            };
            socket.send(JSON.stringify(data));
            messageInput.value = '';
        }
    }

    function joinGroup() {
        const groupName = prompt('请输入要加入的分组名');
        if (groupName) {
            const data = {
                type: 'joinGroup',
                groupName: groupName
            };
            socket.send(JSON.stringify(data));
        }
    }
</script>
</body>
</html>